﻿using System;
using System.Text;

namespace FastDFS.Client
{
    public abstract class StructBase
    {
        protected class FieldInfo
        {
            public FieldInfo(string name, int offset, int size)
            {
                this.Name = name;
                this.Offset = offset;
                this.Size = size;
            }

            public string Name { get; private set; }
            public int Offset { get; private set; }
            public int Size { get; private set; }
        }

        public abstract void SetFields(byte[] bs, int offset);

        protected string StringValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            try
            {
                return Encoding.GetEncoding(ClientGlobal.Charset).GetString(bs, offset + filedInfo.Offset, filedInfo.Size).Replace("\0", "").Trim();
            }
            catch (Exception ex)
            {
                throw new Exception("Can not convert bytes to string",ex);
            }
        }

        protected long LongValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return ProtoCommon.Buff2Long(bs, offset + filedInfo.Offset);
        }

        protected int IntValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return (int)ProtoCommon.Buff2Long(bs, offset + filedInfo.Offset);
        }

        protected int Int32Value(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return ProtoCommon.Buff2Int(bs, offset + filedInfo.Offset);
        }

        protected byte ByteValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return bs[offset + filedInfo.Offset];
        }

        protected bool BooleanValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return bs[offset + filedInfo.Offset] != 0;
        }

        protected DateTime DateValue(byte[] bs, int offset, FieldInfo filedInfo)
        {
            return ProtoCommon.UnixTimestampToDateTime(ProtoCommon.Buff2Long(bs, offset + filedInfo.Offset));
        }
    }
}
